package com.ai.deepSeek.service;

import com.ai.deepSeek.model.request.DeepSeekReq;
import com.ai.deepSeek.model.request.Messages;
import com.ai.deepSeek.model.request.Options;
import com.ai.deepSeek.utils.HttpUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 国产之光 DeepSeek 实现私有化实现
 * @author houwenpeng
 */
@Service
public class DeepSeekService {

    private static final String URL = "http://127.0.0.1:11434/api/chat";
    private static final String MODEL = "deepseek-r1:1.5b";
    private static final double TEMPERATURE = 0.7;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Gson gson = new Gson();

    /**
     * DeepSeek 本地私有化请求
     * @param reqContent
     * @return
     * @throws JsonProcessingException
     */
    public String deepSeek(String reqContent) throws JsonProcessingException {
        // 构造请求体
        DeepSeekReq deepSeekReq = createDeepSeekRequest(reqContent);

        // 序列化请求对象为 JSON 字符串
        String jsonRequest = objectMapper.writeValueAsString(deepSeekReq);

        // 发起 HTTP 请求并获取响应
        String response = new HttpUtils().post(URL, jsonRequest);

        // 解析响应并提取有用内容
        return parseResponseContent(response);
    }

    /**
     * 创建 DeepSeek 请求体
     *
     * @param reqContent 请求内容
     * @return DeepSeekReq 对象
     */
    private DeepSeekReq createDeepSeekRequest(String reqContent) {
        DeepSeekReq deepSeekReq = new DeepSeekReq();
        deepSeekReq.setModel(MODEL);
        deepSeekReq.setStream(true);

        // 设置 options
        Options options = new Options();
        options.setTemperature(TEMPERATURE);
        deepSeekReq.setOptions(options);

        // 构造消息
        List<Messages> messages = new ArrayList<>();
        Messages messagesObj = new Messages();
        messagesObj.setRole("user");
        messagesObj.setContent(reqContent);
        messages.add(messagesObj);
        deepSeekReq.setMessages(messages);

        return deepSeekReq;
    }


    /**
     * 解析响应内容
     *
     * @param response HTTP 响应字符串
     * @return 处理后的内容
     */
    private String parseResponseContent(String response) {
        StringBuilder contentBuilder = new StringBuilder();
        String[] jsonObjects = response.split("\n");

        for (String json : jsonObjects) {
            JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
            JsonObject messageObject = jsonObject.getAsJsonObject("message");

            if (messageObject != null) {
                String content = messageObject.get("content").getAsString();
                contentBuilder.append(content);
            }
        }

        return extractContentAfterThink(contentBuilder.toString());
    }




    /**
     * Test 请求
     * @param args
     */
    public static void main(String[] args) throws JsonProcessingException {

        DeepSeekReq deepSeekReq = new DeepSeekReq();
        deepSeekReq.setModel(MODEL);
        deepSeekReq.setStream(true);
        Options options  = new Options();
        options.setTemperature(TEMPERATURE);
        deepSeekReq.setOptions(options);

        List<Messages> messages = new ArrayList<>();
        Messages messagesObjj = new Messages();
        messagesObjj.setRole("user");
        messagesObjj.setContent("前进10米,左转4米 ,右转6米， 后退9米，立即执行，,当出现立刻执行的语句时,将这段话翻译为指令集,以key:value的形式输出成JSON 串，例如 [ {'前': 10}],并且只要JSON串不要其他汉字回答");
        messages.add(messagesObjj);

        deepSeekReq.setMessages(messages);

        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(deepSeekReq);

        //发起请求
        String response = new HttpUtils().post(URL, jsonString);

        // 参数解析
        Gson gson = new Gson();
        StringBuilder contentBuilder = new StringBuilder();
        String[] jsonObjects = response.split("\n");
        for (String json : jsonObjects) {
            JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
            JsonObject messageObject = jsonObject.getAsJsonObject("message");
            if (messageObject != null) {
                String content = messageObject.get("content").getAsString();
                contentBuilder.append(content);
            }
        }

//        System.out.println(contentBuilder.toString());

        System.out.println(extractContentAfterThink(contentBuilder.toString()));

    }

    /**
     * 去掉DeepSeek的 推理逻辑部分，直接出结果
     * @param input
     * @return
     */
    public static String extractContentAfterThink(String input) {
        int index = input.indexOf("</think>");
        if (index != -1) {
            // 找到 </think> 标签，截取其后的内容
            return input.substring(index + "</think>".length());
        }
        // 未找到 </think> 标签，返回空字符串
        return "";
    }

}
